import os
import re
import shutil
import time
import uuid
import sys
import subprocess
# 加载配置文件
def load_config(config_path):
    with open(config_path, 'r', encoding='utf-8') as file:
        lines = file.readlines()
    config = {}
    for line in lines:
        match = re.match(r"\{ text: '(.*)', link: '(.*)' \},", line.strip())
        if match:
            text, link = match.groups()
            config[text] = link
    return config

# 提取一级标题对应的章节内容
def extract_first_level_sections(file_path):
    with open(file_path, 'r', encoding='utf-8') as file:
        content = file.read()

    sections = re.split(r'(?=\n# )', content)
    sections_dict = {}
    for section in sections:
        header_match = re.match(r'\n# (.+)', section)
        if header_match:
            header = header_match.group(1).strip()
            if header not in sections_dict:
                sections_dict[header] = section.strip()
            else:
                sections_dict[header] += '\n' + section.strip()
    return sections_dict

# 确保目录存在
def ensure_dir_exists(directory):
    if not os.path.exists(directory):
        os.makedirs(directory)

# 生成唯一文件名
def generate_unique_filename(dir_name, ext, image_target_dir):
    base_name = f"{dir_name}_{time.strftime('%Y%m%d_%H%M%S')}"
    unique_name = f"{base_name}.{ext}"
    while os.path.exists(os.path.join(image_target_dir, unique_name)):
        unique_suffix = f"_{uuid.uuid4().hex[:8]}"
        unique_name = f"{base_name}{unique_suffix}.{ext}"
    return unique_name

# 处理图片路径
def process_images(markdown_content, image_source_dir, image_target_dir, path_prefix):
    def replace_image_path(match):
        img_path = match.group(1)
        img_name = os.path.basename(img_path)
        img_ext = img_name.split('.')[-1]
        img_dir_name = os.path.basename(image_target_dir)
        
        # 生成唯一名称和目标路径
        unique_name = generate_unique_filename(img_dir_name, img_ext, image_target_dir)
        img_target_path = os.path.join(image_target_dir, unique_name)
        
        # 确保目标目录存在
        os.makedirs(image_target_dir, exist_ok=True)
        
        # 复制图片到目标目录
        img_source_path = os.path.join(image_source_dir, img_name)
        if os.path.exists(img_source_path):
            shutil.copy(img_source_path, img_target_path)
        
        # 处理路径，确保使用正斜杠
        normalized_path = os.path.normpath(os.path.join(path_prefix, img_dir_name, unique_name)).replace('\\', '/')
        
        # 返回包含前缀的新相对路径
        return f'![]({normalized_path})'
    
    updated_content = re.sub(r'!\[\]\(([^)]+)\)', replace_image_path, markdown_content)
    return updated_content

# 提取指定级别标题对应的章节内容
def extract_sections(file_path, level):
    with open(file_path, 'r', encoding='utf-8') as file:
        content = file.read()

    # 根据级别生成正则表达式
    header_pattern = r'(?=\n{} )'.format('#' * level)
    sections = re.split(header_pattern, content)
    sections_dict = {}
    for section in sections:
        header_match = re.match(r'\n{} (.+)'.format('#' * level), section)
        if header_match:
            header = header_match.group(1).strip()
            if header not in sections_dict:
                sections_dict[header] = section.strip()
            else:
                sections_dict[header] += '\n' + section.strip()
    return sections_dict

# 居中处理图片
def process_markdown(file_path):
    with open(file_path, 'r', encoding='utf-8') as file:
        content = file.read()

    # 正则表达式匹配图片链接
    img_pattern = r'!\[.*?\]\(.*?\)'
    images = re.findall(img_pattern, content)

    # 用于存储新的内容
    new_content = []
    center_open = False

    for line in content.split('\n'):
        if re.search(img_pattern, line):
            if not center_open:
                new_content.append('<center>')
                new_content.append(' ')
                center_open = True
            new_content.append(line)
        else:
            if center_open:
                new_content.append(' ')
                new_content.append('</center>')
                center_open = False
            new_content.append(line)
    
    # 处理最后一组图片
    if center_open:
        new_content.append(' ')
        new_content.append('</center>')

    with open(file_path, 'w', encoding='utf-8') as file:
        file.write('\n'.join(new_content))

def down_feishu_md(feishu_path):
    # 获取当前用户目录的路径
    user_directory = os.path.expanduser("~")

    # 获取应该复制到的目录路径
    destination_directory = os.path.join(user_directory, 'AppData', 'Roaming', 'feishu2md')

    # 确保目标目录存在
    if not os.path.exists(destination_directory):
        os.makedirs(destination_directory)

    # 获取文件路径
    source_file = 'config.json'  # 替换为目标文件的完整路径

    # 复制文件
    shutil.copyfile(source_file, os.path.join(destination_directory, 'config.json'))

    args = [
        r'./feishu2md.exe',  # 要执行的程序
        'dl',  # 第一个参数
        feishu_path  # 第二个参数
    ]
    # 执行程序
    result = subprocess.run(args, capture_output=True, text=True)
    # 检查结果
    print(args)
    print('Exit code:', result.returncode)
    print('Program output:', result.stdout)
    print('Error output:', result.stderr)
    
def main():
    # 菜单提示
    print("请选择一个操作：")
    print("1. 下载飞书文档到本地")
    print("2. 居中处理Markdown文件中的图片")
    print("3. 提取Markdown文件的标题生成配置")
    print("4. 处理Markdown文件并更新图片路径")
    
    choice = input("请输入你的选择(1/2/3/4): ")

    if choice == '1':
        feishu_path = input("请输入飞书文档链接：")
        down_feishu_md(feishu_path)

    elif choice == '2':
        markdown_path = input("请输入Markdown文件路径：")
        process_markdown(markdown_path)

        print("图片居中处理完成！")

    elif choice == '3':
        markdown_path = input("请输入Markdown文件路径：")
        title_level = input("请选择要提取的标题级别(1: 一级标题, 2: 二级标题): ")
        title_level = int(title_level)

        headers = extract_sections(markdown_path, title_level)
        for header in headers:
            print(f"{{ text: '{header}', link: 'xxxx' }},")

    elif choice == '4':
        markdown_path = input("请输入Markdown文件路径：")
        config_path = input("请输入配置文件路径：")
        image_source_dir = input("请输入图片源目录路径：")
        path_prefix = input("请输入路径前缀：")

        title_level = input("请选择要处理的标题级别(1: 一级标题, 2: 二级标题): ")
        title_level = int(title_level)

        config = load_config(config_path)
        sections_dict = extract_sections(markdown_path, title_level)
        output_dir = os.path.splitext(markdown_path)[0]
        
        if not os.path.exists(output_dir):
            os.makedirs(output_dir)
        
        for header, link in config.items():
            if header in sections_dict:
                section_output_path = os.path.join(output_dir, link)
                image_target_dir = os.path.join(output_dir, os.path.splitext(link)[0])
                # 生成相应的图片目录
                if not os.path.exists(image_target_dir):
                    os.makedirs(image_target_dir)
                
                # 处理Markdown内容
                updated_content = process_images(sections_dict[header], image_source_dir, image_target_dir, path_prefix)
                
                with open(section_output_path, 'w', encoding='utf-8') as output_file:
                    output_file.write(updated_content)

        print("Markdown文件处理完成！")

    else:
        print("无效的选择，请重新运行程序并选择正确的选项。")

if __name__ == '__main__':
    main()